package cn.ciis.ciis.enterprise;

import cn.ciis.basic.base.BaseCache;
import cn.ciis.basic.base.BaseController;
import cn.ciis.basic.kit.CiisKit;
import cn.ciis.basic.kit.J2CacheKit;
import cn.ciis.basic.model.Enterprise;
import cn.ciis.basic.plugin.CiisPlugs;
import cn.ciis.sys.permission.Notes;
import cn.ciis.sys.permission.Remark;
import cn.hutool.core.date.DateUtil;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import org.tio.core.Tio;

import java.util.Date;

/**
 * 企业信息管理控制器
 * 描述：
 * @author 冉志林
 */
public class EnterpriseAdminController extends BaseController {

    @Inject EnterpriseAdminService srv;

	@Notes(value = "企业信息管理")
    @Remark(value = "企业信息列表")
    public void index() {
        Enterprise mode = getModel(Enterprise.class, "", true);
        kModel(mode, srv.paginate(getInt(PAGENUMBER, 1), getInt(PAGESIZE, 10), mode));
    }

    @Remark(value = "企业信息添加或编辑页")
    public void addOrEdit(Integer id) {
        kAddOrEdit(srv.findById(id));
    }

    @Remark(value = "企业信息保存或修改")
    @Before(EnterpriseAdminValidator.class)
    public void saveOrUpdate() {
        Enterprise bean = getBean(Enterprise.class);
        bean.setCreateAc(getLoginAccountId());
        bean.setCreateAt(new Date());
        Ret ret = srv.saveOrUpdate(bean);
        if (ret.isOk()){
            J2CacheKit.set(BaseCache.ENTERPRISE_TIMED_CACHE,bean.getCode(),(Enterprise) srv.findByFiled("code",bean.getCode()));
        }
        renderJson(ret);
    }

    @Remark(value = "企业信息删除")
    public void deletes(String ids) {
        Ret ret = srv.logicalDeletion(ids,"isDel","1");
        if (ret.isOk()) {
            String[] split = ids.split(",");
            for (String s : split) {
                Enterprise enterprise = (Enterprise) srv.findById(s);
                J2CacheKit.set(BaseCache.ENTERPRISE_TIMED_CACHE,enterprise.getCode(),new Enterprise());
                Tio.closeGroup(CiisPlugs.ciisServerTioConfig,enterprise.getCode(),"企业删除。关闭该企业下所有设备的连接");
            }
        }
        renderJson(ret);
    }
}